package com.gxstnu.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gxstnu.entity.ChatMessage;
import com.gxstnu.exception.CustomerException;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AIService {

    // 这里应该从配置文件中读取API密钥
    @Value("${deepseek.api.key:sk-aa3d0fcfb1c440a2be626047ea3ad0f5}")
    private String apiKey;

    private final OkHttpClient client = new OkHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    // 模拟数据库存储聊天历史
    private final List<ChatMessage> chatHistory = new ArrayList<>();

    /**
     * 调用DeepSeek API获取回答
     */
    public String getAIResponse(String question) {
        try {
            // 构建请求体
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", "deepseek-chat");
            
            ArrayNode messagesArray = objectMapper.createArrayNode();
            ObjectNode userMessage = objectMapper.createObjectNode();
            userMessage.put("role", "user");
            userMessage.put("content", question);
            messagesArray.add(userMessage);
            
            requestBody.set("messages", messagesArray);
            
            // 创建请求
            Request request = new Request.Builder()
                    .url("https://api.deepseek.com/v1/chat/completions")
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .post(RequestBody.create(
                            requestBody.toString(),
                            MediaType.parse("application/json")
                    ))
                    .build();

            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            
            if (!response.isSuccessful()) {
                throw new CustomerException("调用AI接口失败: " + responseBody);
            }

            // 解析响应
            JsonNode jsonResponse = objectMapper.readTree(responseBody);
            String answer = jsonResponse.path("choices").path(0).path("message").path("content").asText();

            // 保存对话历史
            saveChat(question, answer);
            
            return answer;
        } catch (IOException e) {
            throw new CustomerException("调用AI接口异常: " + e.getMessage());
        }
    }

    /**
     * 保存聊天记录
     */
    private void saveChat(String question, String answer) {
        // 保存用户问题
        ChatMessage userMessage = new ChatMessage();
        userMessage.setRole("user");
        userMessage.setContent(question);
        userMessage.setTimestamp(new Date());
        chatHistory.add(userMessage);

        // 保存AI回答
        ChatMessage aiMessage = new ChatMessage();
        aiMessage.setRole("ai");
        aiMessage.setContent(answer);
        aiMessage.setTimestamp(new Date());
        chatHistory.add(aiMessage);
        
        // 实际项目中应该将聊天记录保存到数据库
    }

    /**
     * 获取聊天历史
     */
    public List<ChatMessage> getChatHistory() {
        // 实际项目中应该从数据库中查询聊天历史
        return chatHistory;
    }
}